package com.example.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.train.business.domain.Daily_Train;
import com.example.train.business.domain.Daily_TrainExample;
import com.example.train.business.domain.Train;
import com.example.train.business.mapper.Daily_TrainMapper;
import com.example.train.business.req.Daily_TrainQueryReq;
import com.example.train.business.req.Daily_TrainSaveReq;
import com.example.train.business.resp.Daily_TrainQueryResp;
import com.example.train.common.resp.PageResp;
import com.example.train.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class Daily_TrainService {
    private static final Logger LOG = LoggerFactory.getLogger(Daily_TrainService.class);

    @Resource
    private Daily_TrainMapper daily_TrainMapper;

    @Resource
    private TrainService trainService;

    @Resource
    private Daily_TrainCarriageService daily_trainCarriageService;

    @Resource
    private Daily_TrainStationService daily_TrainStationService;

    @Resource
    private Daily_TrainSeatService daily_TrainSeatService;

    @Resource
    private Daily_TrainTicketService daily_trainTicketService;


    /**
     * 乘客注册请求的服务类
     * @param req
     */
    public void save(Daily_TrainSaveReq req) {
        DateTime now = DateTime.now();
        Daily_Train daily_Train = BeanUtil.copyProperties(req, Daily_Train.class);
        if(ObjectUtil.isNull(daily_Train.getId())){
            //在service中对以下三种数据赋值，因为请求参数不带这三个值，需要服务端自行设置
            daily_Train.setId(SnowUtil.getSnowflakeNextId());
            daily_Train.setCreateTime(now);
            daily_Train.setUpdateTime(now);
            daily_TrainMapper.insert(daily_Train);
        }else{
            daily_Train.setUpdateTime(now);
            daily_TrainMapper.updateByPrimaryKey(daily_Train);
        }
    }
    public PageResp<Daily_TrainQueryResp> queryList(Daily_TrainQueryReq req) {
        Daily_TrainExample daily_TrainExample = new Daily_TrainExample();
        daily_TrainExample.setOrderByClause("date asc,code asc");
        Daily_TrainExample.Criteria criteria = daily_TrainExample.createCriteria();
        if(ObjectUtil.isNotEmpty(req.getCode())){
            criteria.andCodeEqualTo(req.getCode());
        }
        if(ObjectUtil.isNotNull(req.getDate())){
            criteria.andDateEqualTo(req.getDate());
        }

        LOG.info("查询页码是 {}", req.getPage());
        LOG.info("每页条数是 {}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Daily_Train> daily_TrainList = daily_TrainMapper.selectByExample(daily_TrainExample);

        PageInfo<Daily_Train> pageInfo = new PageInfo<>(daily_TrainList);
        LOG.info("总行数是 {}", pageInfo.getTotal());
        LOG.info("总页数是 {}", pageInfo.getPages());

        List<Daily_TrainQueryResp> list = BeanUtil.copyToList(daily_TrainList, Daily_TrainQueryResp.class);

        PageResp<Daily_TrainQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 删除乘客信息的服务实现
     * @param id
     */
    public void delete(Long id) {
        daily_TrainMapper.deleteByPrimaryKey(id);
    }

    /**
     * 生成某日所有车次信息，包括车次、车站、车厢、座位
     * @param date
     */
    public void genDaily(Date date) {
        List<Train> trainList = trainService.selectAll();
        if (CollUtil.isEmpty(trainList)) {
            LOG.info("没有车次基础数据，任务结束");
            return;
        }

        for (Train train : trainList) {
            genDailyTrain(date, train);
        }
    }

    @Transactional
    public void genDailyTrain(Date date, Train train) {
        LOG.info("生成日期【{}】车次【{}】的信息开始", DateUtil.formatDate(date), train.getCode());

        // 删除该车次已有的数据
        Daily_TrainExample dailyTrainExample = new Daily_TrainExample();
        dailyTrainExample.createCriteria()
                .andDateEqualTo(date)
                .andCodeEqualTo(train.getCode());
        daily_TrainMapper.deleteByExample(dailyTrainExample);

        // 生成该车次的数据
        DateTime now = DateTime.now();
        Daily_Train dailyTrain = BeanUtil.copyProperties(train, Daily_Train.class);
        dailyTrain.setId(SnowUtil.getSnowflakeNextId());
        dailyTrain.setCreateTime(now);
        dailyTrain.setUpdateTime(now);
        dailyTrain.setDate(date);
        daily_TrainMapper.insert(dailyTrain);

        // 生成该车次的车站数据
        daily_TrainStationService.genDaily(date, train.getCode());

        //生成车次的车厢信息
        daily_trainCarriageService.genDaily(date, train.getCode());

        //生成座位信息
        daily_TrainSeatService.genDaily(date, train.getCode());

        //生成余票信息
        daily_trainTicketService.genDaily(dailyTrain,date, train.getCode());

        LOG.info("生成日期【{}】车次【{}】的信息结束", DateUtil.formatDate(date), train.getCode());


    }

}
